package com.javaee.ch12.web.api;

import com.javaee.ch12.common.response.ResultVo;
import com.javaee.ch12.entity.User;
import com.javaee.ch12.service.UserService;
import com.javaee.ch12.web.dto.LoginDto;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Validated
@RestController
@RequestMapping("")
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    HttpServletRequest request;

    @PostMapping("/api/login")
    public ResultVo login(@RequestBody @Valid LoginDto loginDto) {
        User user = userService.authenticateUser(loginDto.getUsername(), loginDto.getPassword());
        System.out.println(loginDto);
        if (user != null) {
            request.getSession().setAttribute("LoginUser", user);
            return ResultVo.ok(user);
        } else {
            return ResultVo.fail("登录失败，用户名或密码错误");
        }
    }

    @PostMapping("/api/logout")
    public ResultVo logout() {
        request.getSession().invalidate();
        return ResultVo.ok("注销成功");
    }
}